/*
 * @lc app=leetcode.cn id=524 lang=javascript
 *
 * [524] 通过删除字母匹配到字典里最长单词
 */

// @lc code=start
/**
 * @param {string} s
 * @param {string[]} dictionary
 * @return {string}
 */
var findLongestWord = function(s, dictionary) {
    // js Array sort 函数的规则是 -1 则a先b后
    // 所以 a-b 即是升序 b-a 降序
    // a > b 可以比较字符串 字典序
    dictionary.sort(
        (a, b) => b.length !== a.length
            ? b.length - a.length
            : (a < b ? -1 : 1)
    )

    // console.log(dictionary)

    for (let word of dictionary) {
        let i = 0, j = 0
        while (i < s.length && j < word.length) {
            if (s[i] === word[j]) j++;
            i++;
        }
        if (j === word.length) {
            return word
        }
    }
    return ''
};
// @lc code=end

console.log(
    // findLongestWord("abpcplea", ["ale","apple","monkey","plea"])
    findLongestWord("abce", ["abe","abc"])
)